# Copyright @Shinji-IkariG
from github import Github  # type: ignore
import csv

def main():
    # 你的 GitHub ID
    GH_USER = 'nomop'
    # 你的个人 token，可以前往 GitHub 设置中的 Developer settings 生成自己的 token
    GH_PAT = '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'

    github = Github(GH_PAT)
    # 需要爬取的开源组织的组织名
    org = github.get_organization('net4people')
    repos = org.get_repos(type='all', sort='full_name', direction='asc')

    # 命名存放贡献者数据的文件
    with open('contributors.csv', 'w', newline='') as csvfile:
        # 爬取哪些数据
        fieldnames = ['contributor']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writeheader()

        contributors_set = set()  # 使用集合以确保贡献者不重复

        for repo in repos:
            print(f"Processing repository: {repo.name}")
            contributors = repo.get_contributors()
            for contributor in contributors:
                contributors_set.add(contributor.login)

                # 检查集合大小
                if len(contributors_set) >= 1000:
                    print("Reached 1000 contributors, stopping the collection.")
                    break
            
            # 如果达到了4000，停止处理
            if len(contributors_set) >= 1000:
                break

        # 写入CSV文件
        for contributor in contributors_set:
            writer.writerow({'contributor': contributor})

    print(f"Successfully wrote {len(contributors_set)} contributors to CSV.")

if __name__ == "__main__":
    main()
